<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Scripts - Definition &amp; Usage | AutoHotkey</title>
<meta name="description" content="Learn details about scripts in general, splitting long lines, compiling a script, passing command line parameters, codepage and debugging." />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="static/theme.css" rel="stylesheet" type="text/css" />
<script src="static/content.js" type="text/javascript"></script>
</head>
<body>

<h1>Scripts</h1>
<p>Related topics:</p>
<ul>
  <li><a href="Program.htm">Using the Program</a>: How to use AutoHotkey, in general.</li>
  <li><a href="Concepts.htm">Concepts and Conventions</a>: General explanation of various concepts utilised by AutoHotkey.</li>
  <li><a href="Language.htm">Scripting Language</a>: Specific details about syntax (how to write scripts).</li>
</ul>

<h2>Table of Contents</h2>
<ul>
  <li><a href="#intro">Introduction</a></li>
  <li><a href="#auto">The Top of the Script (the Auto-execute Section)</a>: This portion executes automatically when the script starts.</li>
  <li><a href="#continuation">Splitting a Long Line into a Series of Shorter Ones</a>: This can improve a script's readability and maintainability.</li>
  <li><a href="#ahk2exe">Convert a Script to an EXE (Ahk2Exe)</a>: Convert a .ahk script into a .exe file that can run on any PC.</li>
  <li><a href="#cmd">Passing Command Line Parameters to a Script</a>: The variables %1%, %2%, etc. contain the incoming parameters.</li>
  <li><a href="#cp">Script File Codepage</a>: Using non-ASCII characters safely in scripts.</li>
  <li><a href="#debug">Debugging a Script</a>: How to find the flaws in a misbehaving script.</li>
</ul>
<h2 id="intro">Introduction</h2>
<p>Each script is a plain text file containing lines to be executed by the program (AutoHotkey.exe). A script may also contain <a href="Hotkeys.htm">hotkeys</a> and <a href="Hotstrings.htm">hotstrings</a>, or even consist entirely of them. However, in the absence of hotkeys and hotstrings, a script will perform its commands sequentially from top to bottom the moment it is launched.</p>
<p>The program loads the script into memory line by line, and each line may be up to 16,383 characters long. During loading, the script is <a href="misc/Performance.htm">optimized</a> and validated. Any syntax errors will be displayed, and they must be corrected before the script can run.</p>
<h2 id="auto">The Top of the Script (the Auto-execute Section)</h2>
<p>After the script has been loaded, it begins executing at the top line, continuing until a <a href="commands/Return.htm">Return</a>, <a href="commands/Exit.htm">Exit</a>, <a href="Hotkeys.htm">hotkey/hotstring label</a>, or the physical end of the script is encountered (whichever comes first). This top portion of the script is referred to as the <em>auto-execute</em> section.</p>
<p class="warning"><strong>Note:</strong> While the script's <em>first</em> hotkey/hotstring label has the same effect as <a href="commands/Return.htm">return</a>, other hotkeys and labels do not.</p>
<p>A script  that is not <a href="commands/_Persistent.htm">persistent</a> and that lacks <a href="Hotkeys.htm">hotkeys</a>, <a href="Hotstrings.htm">hotstrings</a>, <a href="commands/OnMessage.htm">OnMessage()</a>, and <a href="commands/Gui.htm">GUI</a> will terminate after the auto-execute section has completed. Otherwise, it will stay running in an idle state, responding to events such as  hotkeys, hotstrings, <a href="commands/Gui.htm#label">GUI events</a>, <a href="commands/Menu.htm">custom menu items</a>, and <a href="commands/SetTimer.htm">timers</a>.</p>
<p>Every <a href="misc/Threads.htm">thread</a> launched by a <a href="Hotkeys.htm">hotkey</a>, <a href="Hotstrings.htm">hotstring</a>, <a href="commands/Menu.htm"> menu item</a>, <a href="commands/Gui.htm#label">GUI event</a>, or <a href="commands/SetTimer.htm">timer</a> starts off fresh with the default values for the following attributes as set in the auto-execute section. If unset, the standard defaults will apply (as documented on each of the following pages): <a href="commands/AutoTrim.htm">AutoTrim</a>, <a href="commands/CoordMode.htm">CoordMode</a>, <a href="commands/Critical.htm">Critical</a>, <a href="commands/DetectHiddenText.htm">DetectHiddenText</a>, <a href="commands/DetectHiddenWindows.htm">DetectHiddenWindows</a>, <a href="commands/FileEncoding.htm">FileEncoding</a>, <a href="commands/ListLines.htm">ListLines</a>, <a href="commands/SendLevel.htm">SendLevel</a>, <a href="commands/SendMode.htm">SendMode</a>, <a href="commands/SetBatchLines.htm">SetBatchLines</a>, <a href="commands/SetControlDelay.htm">SetControlDelay</a>, <a href="commands/SetDefaultMouseSpeed.htm">SetDefaultMouseSpeed</a>, <a href="commands/SetFormat.htm">SetFormat</a>, <a href="commands/SetKeyDelay.htm">SetKeyDelay</a>, <a href="commands/SetMouseDelay.htm">SetMouseDelay</a>, <a href="commands/SetRegView.htm">SetRegView</a>, <a href="commands/SetStoreCapslockMode.htm">SetStoreCapsLockMode</a>, <a href="commands/SetTitleMatchMode.htm">SetTitleMatchMode</a>, <a href="commands/SetWinDelay.htm">SetWinDelay</a>, <a href="commands/StringCaseSense.htm">StringCaseSense</a>, and <a href="commands/Thread.htm">Thread</a>.</p>
<p>If the auto-execute section takes a long time to complete (or never completes), the default values for the above settings will be put into effect after 100 milliseconds. When the auto-execute section finally completes (if ever), the defaults are updated again to be those that were in effect at the end of the auto-execute section. Thus, it's usually best to make any desired changes to the defaults at the top of scripts that contain <a href="Hotkeys.htm">hotkeys</a>, <a href="Hotstrings.htm">hotstrings</a>, <a href="commands/SetTimer.htm">timers</a>, or <a href="commands/Menu.htm">custom menu items</a>. Also note that each <a href="misc/Threads.htm">thread</a> retains its own collection of the above settings. Changes made to those settings will not affect other <a href="misc/Threads.htm">threads</a>.</p>

<h2 id="continuation">Splitting a Long Line into a Series of Shorter Ones</h2>
<p>Long lines can be divided up into a collection of smaller ones to improve readability and maintainability. This does not reduce the script's execution speed because such lines are merged in memory the moment the script launches.</p>
<p id="continuation-line"><strong>Method #1</strong>: A line that starts with &quot;and&quot;, &quot;or&quot;,  ||, &amp;&amp;, a comma, or a <a href="Variables.htm#concat">period</a> is automatically merged with the line directly above it (in v1.0.46+, the same is true for all other <a href="Variables.htm#Operators">expression operators</a> except ++ and --). In the following example, the second line is appended to the first because it begins with a comma:</p>
<pre>FileAppend, This is the text to append.`n   <em>; A comment is allowed here.</em>
    , %A_ProgramFiles%\SomeApplication\LogFile.txt  <em>; Comment.</em></pre>
<p>Similarly, the following lines would get merged into a single line because the last two start with &quot;and&quot; or &quot;or&quot;:</p>
<pre>if (Color = &quot;Red&quot; or Color = &quot;Green&quot;  or Color = &quot;Blue&quot;   <em>; Comment.</em>
    <strong>or</strong> Color = &quot;Black&quot; or Color = &quot;Gray&quot; or Color = &quot;White&quot;)   <em>; Comment.</em>
    <strong>and</strong> ProductIsAvailableInColor(Product, Color)   <em>; Comment.</em></pre>
<p>The <a href="Variables.htm#ternary">ternary operator</a> is also a good candidate:</p>
<pre>ProductIsAvailable := (Color = &quot;Red&quot;)
    <strong>?</strong> false  <em>; We don't have any red products, so don't bother calling the function.</em>
    <strong>:</strong> ProductIsAvailableInColor(Product, Color)</pre>
<p>Although the indentation used in the examples above is optional, it might improve clarity by indicating which lines belong to ones above them. Also, it is not necessary to include extra spaces for lines starting with the words &quot;AND&quot; and &quot;OR&quot;; the program does this automatically. Finally, blank lines or <a href="Language.htm#comments">comments</a> may be added between or at the end of any of the lines in the above examples.</p>
<p id="continuation-section"><strong>Method #2</strong>: This method should be used to merge a large number of lines or when the lines are not suitable for Method #1. Although this method is especially useful for <a href="Hotstrings.htm">auto-replace hotstrings</a>, it can also be used with any command or <a href="Variables.htm#Expressions">expression</a>. For example:</p>
<pre><em>; EXAMPLE #1:</em>
Var =
(
Line 1 of the text.
Line 2 of the text. By default, a linefeed (`n) is present between lines.
)

<em>; EXAMPLE #2:</em>
FileAppend,  <em>; The comma is required in this case.</em>
(
A line of text.
<i>By default</i>, the hard carriage return (Enter) between the previous line and this one will be written to the file as a linefeed (`n).
    <i>By default</i>, the tab to the left of this line will also be written to the file (the same is true for spaces).
<i>By default</i>, variable references such as %Var% are resolved to the variable's contents.
), C:\My File.txt</pre>
<p>In the examples above, a series of lines is bounded at the top and bottom by a pair of parentheses. This is known as a <em>continuation section</em>. Notice that the bottom line contains <a href="commands/FileAppend.htm">FileAppend</a>'s last parameter after the closing parenthesis. This practice is optional; it is done in cases like this so that the comma will be seen as a parameter-delimiter rather than a literal comma.</p>
<p>The default behavior of a continuation section can be overridden by including one or more of the following options to the right of the section's opening parenthesis. If more than one option is present, separate each one from the previous with a space. For example: <code>( LTrim Join| %</code>.</p>
<p id="Join"><strong>Join</strong>: Specifies how lines should be connected together. If this option is omitted, each line except the last will be followed by a linefeed character (`n). If the word <em>Join</em> is specified by itself, lines are connected directly to each other without any characters in between. Otherwise, the word <em>Join</em> should be followed immediately by as many as 15 characters. For example, <code>Join`s</code> would insert a space after each line except the last (&quot;`s&quot; indicates a literal space -- it is a special escape sequence recognized only by <em>Join</em>). Another example is <code>Join`r`n</code>, which inserts CR+LF between lines. Similarly, <code>Join|</code> inserts  a pipe between lines. To have the final line in the section also ended by a join-string, include a blank line immediately above the section's closing parenthesis.</p>
<p>Known limitation: If the Join string ends with a colon, it must not be the last option on the line. For example, <code>(Join:</code> is treated as the label "(Join" and <code>(LTrim Join:</code> is unsupported, but <code>(Join: C</code> is okay.</p>
<p id="LTrim"><strong>LTrim</strong>: Omits spaces and tabs at the beginning of each line. This is primarily used to allow the continuation section to be indented. Also, this option may be turned on for multiple continuation sections by specifying <code>#LTrim</code> on a line by itself. <code>#LTrim</code> is positional: it affects all continuation sections physically beneath it. The setting may be turned off via <code>#LTrim Off</code>.</p>
<p><strong>RTrim0</strong> (RTrim followed by a zero): Turns off the omission of spaces and tabs from the end of each line.</p>
<p id="CommentOption"><strong>Comments</strong> (or <strong>Comment</strong> or <strong>Com</strong> or <strong>C</strong>) <span class="ver">[v1.0.45.03+]</span>: Allows <a href="Language.htm#comments">semicolon comments</a> inside the continuation section (but not <code>/*..*/</code>). Such comments (along with any spaces and tabs to their left) are entirely omitted from the joined result rather than being treated as literal text. Each comment can appear to the right of a line or on a new line by itself.</p>
<p><strong>%</strong> (percent sign): Treats percent signs as literal rather than as variable references. This avoids the need to <a href="commands/_EscapeChar.htm">escape</a> each percent sign to make it literal. This option is not needed in places where percent signs are already literal, such as <a href="Hotstrings.htm">auto-replace hotstrings</a>.</p>
<p><strong>,</strong> (comma): Treats commas as delimiters rather than as literal commas. This rarely-used option is necessary only for the commas between command parameters because in <a href="Functions.htm">function calls</a>, the type of comma does not matter. Also, this option transforms only those commas that actually delimit parameters. In other words, once the command's final parameter is reached (or there are no parameters), subsequent commas are treated as literal commas regardless of this option.</p>
<p id="accent"><strong>`</strong> (accent): Treats each backtick character literally rather than as an <a href="commands/_EscapeChar.htm">escape character</a>. This also prevents commas and percent signs from being explicitly and individually escaped. In addition, it prevents the translation of any explicitly specified escape sequences such as `r and `t.</p>
<p id="non-continuation"><strong>)</strong> <span class="ver">[v1.1.01+]</span>: If a closing parenthesis appears in the continuation section's options (except as a parameter of the <a href="#Join">Join</a> option), the line is reinterpreted as an expression instead of the beginning of a continuation section. This allows expressions like <code>(x.y)[z]()</code> to work without the need to escape the opening parenthesis.</p>
<p><u>Remarks</u></p>
<p><a href="commands/_EscapeChar.htm">Escape sequences</a> such as `n (linefeed) and `t (tab) are supported inside the continuation section except when the <a href="#accent">accent (`) option</a> has been specified.</p>
<p>When the <a href="#CommentOption">comment option</a> is absent, semicolon and /*..*/ comments are not supported within the interior of a continuation section because they are seen as literal text. However, comments can be included on the bottom and top lines of the section. For example:</p>
<pre>FileAppend,   <em>; Comment.
; Comment.</em>
( LTrim Join    <em>; Comment.</em>
    &nbsp;; This is <strong>not</strong> a comment; it is literal. Include the word <i>Comments</i> in the line above to make it a comment.
), C:\File.txt   <em>; Comment.</em></pre>
<p>As a consequence of the above, semicolons never need to be <a href="commands/_EscapeChar.htm">escaped</a> within a continuation section.</p>
<p>A continuation section cannot produce a line whose total length is greater than 16,383 characters (if it tries, the program will alert you the moment the script is launched). One way to work around this is to do a series of concatenations into a variable.  For example:</p>
<pre>Var =
(
...
)
Var = %Var%`n  <em>; Add more text to the variable via another continuation section.</em>
(
...
)
FileAppend, %Var%, C:\My File.txt</pre>
<p>Since a closing parenthesis indicates the end of a continuation section, to have a line start with literal closing parenthesis, precede it with an accent/backtick: <code>`)</code>.</p>
<p>A continuation section can be immediately followed by a line containing the open-parenthesis of another continuation section. This allows the options mentioned above to be varied during the course of building a single line.</p>
<p>The piecemeal construction of a continuation section by means of <a href="commands/_Include.htm">#Include</a> is not supported.</p>

<h2 id="ahk2exe">Convert a Script to an EXE (Ahk2Exe)</h2>
<p>A script compiler (courtesy of fincs, with additions by TAC109) is included with the program.</p>
<p>Once a script is compiled, it becomes a standalone executable; that is, AutoHotkey.exe is not required in order to run the script. The compilation process creates an executable file which contains the following: the AutoHotkey interpreter, the script, any files it <a href="commands/_Include.htm">includes</a>, and any files it has incorporated via the <a href="commands/FileInstall.htm">FileInstall</a> command. <span class="ver">[v1.1.33+]:</span> Additional files can be included using <a href="misc/Ahk2ExeDirectives.htm">Compiler Directives</a>.</p>
<p>Ahk2Exe can be used in the following ways:</p>
<ul>
  <li>
    <p><strong>GUI Interface</strong>: Run the &quot;Convert .ahk to .exe&quot; item in the Start Menu.</p>
  </li>
  <li>
    <p><strong>Right-click</strong>: Within an open Explorer window, you can right-click any .ahk file and select &quot;Compile Script&quot; (only available if the script compiler option was chosen when AutoHotkey was installed). This creates an EXE file of the same base filename as the script, which appears after a short time in the same directory. Note: The EXE file is produced using the same custom icon, .bin file and <a href="#mpress">compression</a> setting that were last used by Method #1 above.</p>
  </li>
  <li id="ahk2exeCmd">
    <p><strong>Command Line</strong>: The compiler can be run from the command line by using the parameters shown below. If any command line parameters are used, the script is compiled immediately unless <code class="no-highlight">/gui</code> is used.</p>
    <style>
      #param_pairs td:not(:last-child) {
        white-space: nowrap;
      }
    </style>
    <table class="info" id="param_pairs">
      <tr>
        <th>Parameter pair</th>
        <th>Meaning</th>
      </tr>
      <tr id="SlashIn">
        <td>/in <i>script_name</i></td>
        <td>The path and name of the script to compile. This is mandatory if any other parameters are used, unless <code class="no-highlight">/gui</code> is used.</td>
      </tr>
      <tr id="SlashOut">
        <td>/out <i>exe_name</i></td>
        <td>The path\name of the output .exe to be created. Default is the directory\base_name of the input file plus extension of .exe.</td>
      </tr>
      <tr id="slashIcon">
        <td>/icon <i>icon_name</i></td>
        <td>The icon file to be used. Default is the last icon used in the GUI interface.</td>
      </tr>
      <tr id="SlashBin">
        <td>/bin <i>file_name</i></td>
        <td>The .bin file to be used. Default is the last .bin file name used in the GUI interface.</td>
      </tr>
      <tr id="SlashCp">
        <td>/cp <i>codepage</i></td>
        <td><span class="ver">[v1.1.23.01+]:</span> Overrides the default codepage used to read script files. For a list of possible values, see <a href="https://docs.microsoft.com/en-au/windows/win32/intl/code-page-identifiers">Code Page Identifiers</a>. Note that Unicode scripts should begin with a byte-order-mark (BOM), rendering the use of this parameter unnecessary.</td>
      </tr>
      <tr id="SlashCompress">
        <td>/compress <i>n</i></td>
        <td><span class="ver">[v1.1.33+]:</span> <a href="#mpress">Compress</a> the exe? 0 = no, 1 = use MPRESS if present, 2 = use UPX if present. Default is the last setting used in the GUI interface.</td>
      </tr>
      <tr id="SlashAhk">
        <td>/ahk <i>file_name</i></td>
        <td><span class="ver">[v1.1.33+]:</span> The path\name of AutoHotkey.exe to be used when compiling the script. Default is AutoHotkey.exe in the directory immediately above that containing the compiler. If not there, the installed Autohotkey.exe is used if present. <span class="ver">[v1.1.33.01+]:</span> Otherwise AutoHotkeyU32.exe in the directory immediately above that containing the compiler is used.</td>
      </tr>
      <tr id="SlashGui">
        <td>/gui</td>
        <td><span class="ver">[v1.1.33+]:</span> Show the GUI instead of immediately compiling. The other parameters can be used to override the settings last used in the GUI. <code>/in</code> is optional in this case.</td>
      </tr>
      <tr id="SlashMpress">
        <td class="warning"><strong>Deprecated:</strong><br>/mpress <i>0or1</i></td>
        <td class="warning"><a href="#mpress">Compress</a> the exe with MPRESS? 0 = no, 1 = yes. Default is the last setting used in the GUI interface.</td>
      </tr>
    </table>
    <p>For example:</p>
    <pre class="no-highlight">Ahk2Exe.exe /in "MyScript.ahk" /icon "MyIcon.ico"</pre>
  </li>
</ul>
<p>Notes:</p>
<ul>
  <li>Parameters containing spaces must be enclosed in double quotes.</li>
  <li>Compiling does not typically improve the performance of a script.</li>
  <li>As of v1.1.01, password protection and the /NoDecompile switch are not supported.</li>
  <li>The commands <a href="commands/_NoTrayIcon.htm">#NoTrayIcon</a> and &quot;<a href="commands/Menu.htm#MainWindow">Menu, Tray, MainWindow</a>&quot; affect the behavior of compiled scripts.</li>
  <li>The built-in variable <a href="Variables.htm#IsCompiled">A_IsCompiled</a> contains 1 if the script is running in compiled form. Otherwise, it is blank.</li>
  <li><span class="ver">[v1.0.43+]:</span> When parameters are passed to Ahk2Exe, a message indicating the success or failure of the compiling process is written to stdout. Although the message will not appear at the command prompt, it can be &quot;caught&quot; by means such as redirecting output to a file. </li>
  <li> <span class="ver">[v1.1.22.03+]:</span> Additionally in the case of a failure, Ahk2Exe has exit codes indicating the kind of error that occurred. These error codes can be found at <a href="https://github.com/AutoHotkey/Ahk2Exe/blob/master/ErrorCodes.md">GitHub (ErrorCodes.md)</a>.</li>
</ul>
<p>The compiler's source code and newer versions can be found at <a href="https://github.com/AutoHotkey/Ahk2Exe">GitHub</a>.</p>

<h3 id="CompilerDirectives">Script Compiler Directives</h3>
<p><span class="ver">[v1.1.33+]:</span> Script compiler directives allow the user to specify details of how a script is to be compiled. Some of the features are:</p>
<ul>
  <li>Ability to change the version information (such as the name, description, version...).</li>
  <li>Ability to add resources to the compiled script.</li>
  <li>Ability to tweak several miscellaneous aspects of compilation.</li>
  <li>Ability to remove code sections from the compiled script and vice versa.</li>
</ul>
<p>See <a href="misc/Ahk2ExeDirectives.htm">Script Compiler Directives</a> for more details.</p>

<h3 id="mpress">Compressing Compiled Scripts</h3>
<p>Ahk2Exe optionally uses MPRESS or <span class="ver">[v1.1.33+]</span> UPX freeware to compress compiled scripts. If <strong>MPRESS.exe</strong> and/or <strong>UPX.exe</strong> has been copied to the "Compiler" subfolder where AutoHotkey was installed, either can be used to compress the .exe as directed by the <code>/compress</code> parameter or the GUI setting. </p>
<p><strong>MPRESS</strong> official website (downloads and information): <a href="http://www.matcode.com/mpress.htm">http://www.matcode.com/mpress.htm</a><br>MPRESS mirror: <a href="https://www.autohotkey.com/mpress/">https://www.autohotkey.com/mpress/</a></p>
<p><strong>UPX</strong> official website (downloads and information): <a href="https://upx.github.io/">https://upx.github.io/</a></p>
<p><strong>Note:</strong> While compressing the script executable prevents casual inspection of the script's source code using a plain text editor like Notepad or a PE resource editor, it does not prevent the source code from being extracted by tools dedicated to that purpose.</p>

<h2 id="cmd">Passing Command Line Parameters to a Script</h2>
<p>Scripts support command line parameters. The format is:</p>
<pre>AutoHotkey.exe [<i>Switches</i>] [<i>Script Filename</i>] [<i>Script Parameters</i>]</pre>
<p>And for compiled scripts, the format is:</p>
<pre>CompiledScript.exe [<i>Switches</i>] [<i>Script Parameters</i>]</pre>
<p><strong>Switches:</strong> Zero or more of the following:</p>
<table class="info">
  <tr><th>Switch</th><th>Meaning</th><th>Works compiled?</th></tr>
  <tr id="SlashF">
    <td>/f or /force</td>
    <td>Launch unconditionally, skipping any warning dialogs. This has the same effect as <a href="commands/_SingleInstance.htm">#SingleInstance Off</a>.</td>
    <td>Yes</td>
  </tr>
  <tr id="SlashR">
    <td>/r or /restart</td>
    <td>Indicate that the script is being restarted (this is also used by the <a href="commands/Reload.htm">Reload</a> command, internally).</td>
    <td>Yes</td>
  </tr>
  <tr id="ErrorStdOut">
    <td>/ErrorStdOut<br><br>/ErrorStdOut=<em>Encoding</em></td>
    <td>
      <p>Send syntax errors that prevent a script from launching to the standard error stream (stderr) rather than displaying a dialog. See <a href="commands/_ErrorStdOut.htm">#ErrorStdOut</a> for details. This can be combined with /iLib to validate the script without running it.</p>
      <p><span class="ver">[v1.1.33+]:</span> An <a href="commands/FileEncoding.htm">encoding</a> can optionally be specified. For example, <code>/ErrorStdOut=UTF-8</code> encodes messages as UTF-8 before writing them to stderr.</p>
    </td>
    <td>Yes</td>
  </tr>
  <tr id="SlashDebug">
    <td>/Debug</td>
    <td><span class="ver">[AHK_L 11+]:</span> Connect to a debugging client. For more details, see <a href="#idebug">Interactive Debugging</a>.</td>
    <td>No</td>
  </tr>
  <tr id="CPn">
    <td>/CP<i>n</i></td>
    <td>
      <p><span class="ver">[AHK_L 51+]:</span> Overrides the default codepage used to read script files. For more details, see <a href="#cp">Script File Codepage</a>.</p>
      <p><span class="ver">[v1.1.33+]:</span> If "Default to UTF-8" is enabled in the installer, the ".ahk" file type is registered with a command line including <code>/CP65001</code>. This causes all scripts launched through the shell (Explorer) to default to UTF-8 in the absence of a UTF-16 byte order mark. Scripts launched by running AutoHotkey.exe directly still default to <code>CP0</code>, as the <code>/CP65001</code> switch is absent.</p>
    </td>
    <td>No</td>
  </tr>
  <tr>
    <td>/iLib <em>"OutFile"</em></td>
    <td>
      <p><span class="ver">[v1.0.47+]:</span> AutoHotkey loads the script but does not run it. For each script file which is auto-included via <a href="Functions.htm#lib">the library mechanism</a>, two lines are written to the file specified by <em>OutFile</em>. These lines are written in the following format, where <em>LibDir</em> is the full path of the Lib folder and <em>LibFile</em> is the filename of the library:</p>
<pre>#Include LibDir\
#IncludeAgain LibDir\LibFile.ahk</pre>
      <p>If the output file exists, it is overwritten. <em>OutFile</em> can be <code>*</code> to write the output to stdout.</p>
      <p>If the script contains syntax errors, the output file may be empty. The process exit code can be used to detect this condition; if there is a syntax error, the exit code is 2. The /ErrorStdOut switch can be used to suppress or capture the error message.</p>
    </td>
    <td>No</td>
  </tr>
</table>

<p id="defaultfile"><strong>Script Filename:</strong> This can be omitted if there are no <em>Script Parameters</em>. If omitted (such as if you run AutoHotkey directly from the Start menu), the program looks for a script file called <code><i>AutoHotkey</i>.ahk</code> in the following locations, in this order:</p>
<ul>
  <li>The directory which contains the <a href="Variables.htm#AhkPath">AutoHotkey executable</a>.</li>
  <li>The current user's <a href="Variables.htm#MyDocuments">Documents</a> folder.</li>
</ul>
<p>The filename <code><i>AutoHotkey</i>.ahk</code> depends on the name of the executable used to run the script. For example, if you rename AutoHotkey.exe to MyScript.exe, it will attempt to find <code>MyScript.ahk</code>. If you run AutoHotkeyU32.exe without parameters, it will look for AutoHotkeyU32.ahk.</p>
<p>Note: In old versions prior to <a href="AHKL_ChangeLog.htm#L51">revision 51</a>, the program looked for AutoHotkey.ini in the working directory or AutoHotkey.ahk in My Documents.</p>
<p><span class="ver">[v1.1.17+]:</span> Specify an asterisk (*) for the filename to read the script text from standard input (stdin). For an example, see <a href="commands/Run.htm#ExecScript">ExecScript()</a>.</p>
<p id="cmd_args"><strong>Script Parameters:</strong> The string(s) you want to pass into the script, with each separated from the next by a space. Any parameter that contains spaces should be enclosed in quotation marks. A literal quotation mark may be passed in by preceding it with a backslash (\&quot;). Consequently, any trailing slash in a quoted parameter (such as &quot;C:\My Documents<span class="red">\&quot;</span>) is treated as a literal quotation mark (that is, the script would receive the string C:\My Documents<span class="red">&quot;</span>). To remove such quotes, use <code><a href="commands/StringReplace.htm">StringReplace</a>, 1, 1, <span class="red">&quot;</span>,, All</code>.</p>
<p><span class="ver">[v1.1.27+]:</span> Incoming parameters, if present, are stored as an array in the built-in variable <strong>A_Args</strong>, and can be accessed using <a href="Objects.htm#Usage_Simple_Arrays">array syntax</a>. <code>A_Args[1]</code> contains the first parameter. The following example exits the script when too few parameters are passed to it:</p>
<pre>if A_Args.Length() &lt; 3
{
    MsgBox % "This script requires at least 3 parameters but it only received " A_Args.Length() "."
    ExitApp
}</pre>
<p>If the number of parameters passed into a script varies (perhaps due to the user dragging and dropping a set of files onto a script), the following example can be used to extract them one by one:</p>
<pre>for n, param in A_Args  <em>; For each parameter:</em>
{
    MsgBox Parameter number %n% is %param%.
}
</pre>
<p>If the parameters are file names, the following example can be used to convert them to their case-corrected long names (as stored in the file system), including complete/absolute path:</p>
<pre>for n, GivenPath in A_Args  <em>; For each parameter (or file dropped onto a script):</em>
{
    Loop Files, %GivenPath%, FD  <em>; Include files and directories.</em>
        LongPath := A_LoopFileFullPath
    MsgBox The case-corrected long path name of file`n%GivenPath%`nis:`n%LongPath%
}</pre>
<p><strong>Known limitation:</strong> dragging files onto a .ahk script may fail to work properly if 8-dot-3 (short) names have been turned off in an NTFS file system. One work-around is to <a href="#ahk2exe">compile</a> the script then drag the files onto the resulting EXE.</p>
<p id="cmd_args_old"><strong>Legacy:</strong> The command line parameters are also stored in the <a href="Variables.htm">variables</a> %1%, %2%, and so on, as in versions prior to <span class="ver">[v1.1.27]</span>. In addition, %0% contains the number of parameters passed (0 if none). However, these variables cannot be referenced directly in an expression because they would be seen as numbers rather than variables. The following example exits the script when too few parameters are passed to it:</p>
<pre>if 0 &lt; 3  <em>; The left side of a <a href="commands/IfEqual.htm">non-expression if-statement</a> is always the name of a variable.</em>
{
    MsgBox This script requires at least 3 incoming parameters but it only received %0%.
    ExitApp
}</pre>
<p>If the number of parameters passed into a script varies (perhaps due to the user dragging and dropping a set of files onto a script), the following example can be used to extract them one by one:</p>
<pre>Loop, %0%  <em>; For each parameter:</em>
{
    param := %A_Index%  <em>; Fetch the contents of the variable whose name is contained in A_Index.</em>
    MsgBox, 4,, Parameter number %A_Index% is %param%.  Continue?
    IfMsgBox, No
        break
}</pre>
<p>If the parameters are file names, the following example can be used to convert them to their case-corrected long names (as stored in the file system), including complete/absolute path:</p>
<pre>Loop %0%  <em>; For each parameter (or file dropped onto a script):</em>
{
    GivenPath := %A_Index%  <em>; Fetch the contents of the variable whose name is contained in A_Index.</em>
    Loop %GivenPath%, 1
        LongPath := A_LoopFileLongPath
    MsgBox The case-corrected long path name of file`n%GivenPath%`nis:`n%LongPath%
}</pre>

<h2 id="cp">Script File Codepage <span class="ver">[AHK_L 51+]</span></h2>
<p>In order for non-ASCII characters to be read correctly from file, the encoding used when the file was saved (typically by the text editor) must match what AutoHotkey uses when it reads the file. If it does not match, characters will be decoded incorrectly. AutoHotkey uses the following rules to decide which encoding to use:</p>
<ul>
  <li>If the file begins with a UTF-8 or UTF-16 (LE) byte order mark, the appropriate codepage is used and the <a href="#CPn">/CP<i>n</i></a> switch is ignored.</li>
  <li>If the <a href="#CPn">/CP<i>n</i></a> switch is passed on the command-line, codepage <i>n</i> is used. For a list of possible values, see <a href="https://docs.microsoft.com/en-au/windows/win32/intl/code-page-identifiers">Code Page Identifiers</a>.
  <p class="note"><strong>Note:</strong> The "Default to UTF-8" option in the AutoHotkey <span class="ver">[v1.1.33+]</span> installer adds <code>/CP65001</code> to the command line for all scripts launched via the shell (Explorer).</p></li>
  <li>In all other cases, the system default ANSI codepage is used.</li>
</ul>
<p>Note that this applies only to script files loaded by AutoHotkey, not to file I/O within the script itself. <a href="commands/FileEncoding.htm">FileEncoding</a> controls the default encoding of files read or written by the script, while <a href="commands/IniRead.htm">IniRead</a> and <a href="commands/IniWrite.htm">IniWrite</a> always deal in UTF-16 or ANSI.</p>
<p>As all text is converted (where necessary) to the <a href="Compat.htm#Format">native string format</a>, characters which are invalid or don't exist in the native codepage are replaced with a placeholder: ANSI '?' or Unicode '&#65533;'. In Unicode builds, this should only occur if there are encoding errors in the script file or the codepages used to save and load the file don't match.</p>
<p><a href="commands/RegWrite.htm">RegWrite</a> may be used to set the default for scripts launched from Explorer (e.g. by double-clicking a file):</p>
<pre><em>; Uncomment the appropriate line below or leave them all commented to
;   reset to the default of the current build.  Modify as necessary:
; codepage := 0        ; System default ANSI codepage
; codepage := 65001    ; UTF-8
; codepage := 1200     ; UTF-16
; codepage := 1252     ; ANSI Latin 1; Western European (Windows)</em>
if (codepage != "")
    codepage := " /CP" . codepage
cmd="%A_AhkPath%"%codepage% "`%1" `%*
key=AutoHotkeyScript\Shell\Open\Command
if A_IsAdmin    <em>; Set for all users.</em>
    RegWrite, REG_SZ, HKCR, %key%,, %cmd%
else            <em>; Set for current user only.</em>
    RegWrite, REG_SZ, HKCU, Software\Classes\%key%,, %cmd%</pre>
<p>This assumes AutoHotkey has already been installed. Results may be less than ideal if it has not.</p>

<h2 id="debug">Debugging a Script</h2>
<p>Commands such as <a href="commands/ListVars.htm">ListVars</a> and <a href="commands/Pause.htm">Pause</a> can help you debug a script. For example, the following two lines, when temporarily inserted at carefully chosen positions, create &quot;break points&quot; in the script:</p>
<pre>ListVars
Pause</pre>
<p>When the script encounters these two lines, it will display the current contents of all variables for your inspection. When you're ready to resume, un-pause the script via the File or Tray menu. The script will then continue until reaching the next &quot;break point&quot; (if any).</p>
<p>It is generally best to insert these &quot;break points&quot; at positions where the active window does not matter to the script, such as immediately before a WinActivate command. This allows the script to properly resume operation when you un-pause it.</p>
<p>The following commands are also useful for debugging: <a href="commands/ListLines.htm">ListLines</a>, <a href="commands/KeyHistory.htm">KeyHistory</a>, and <a href="commands/OutputDebug.htm">OutputDebug</a>.</p>
<p>Some common errors, such as typos and missing "global" declarations, can be detected by <a href="commands/_Warn.htm">enabling warnings</a>.</p>
<h3 id="idebug">Interactive Debugging <span class="ver">[AHK_L 11+]</span></h3>
<p>Interactive debugging is possible with a supported <a href="AHKL_DBGPClients.htm">DBGp client</a>. Typically the following actions are possible:</p>
<ul>
  <li>Set and remove breakpoints on lines - pause execution when a <a href="https://en.wikipedia.org/wiki/Breakpoint">breakpoint</a> is reached.</li>
  <li>Step through code line by line - step into, over or out of functions and subroutines.</li>
  <li>Inspect all variables or a specific variable.</li>
  <li>View the stack of running subroutines and functions.</li>
</ul>
<p>Note that this functionality is disabled for compiled scripts.</p>
<p>To enable interactive debugging, first launch a supported debugger client then launch the script with the <b>/Debug</b> command-line switch.</p>
<pre class="Syntax">AutoHotkey.exe /Debug<span class="optional">=<i>SERVER</i>:<i>PORT</i></span> ...</pre>
<p><i>SERVER</i> and <i>PORT</i> may be omitted.  For example, the following are equivalent:</p>
<pre class="no-highlight">AutoHotkey /Debug "myscript.ahk"
AutoHotkey /Debug=localhost:9000 "myscript.ahk"</pre>
<p id="debug_attach"><span class="ver">[AHK_L 59+]:</span> To attach the debugger to a script which is already running, send it a message as shown below:</p>
<pre>ScriptPath := "" <em>; SET THIS TO THE FULL PATH OF THE SCRIPT</em>
DetectHiddenWindows On
if WinExist(ScriptPath " ahk_class AutoHotkey")
    <em>; Optional parameters:
    ;   wParam  = the IPv4 address of the debugger client, as a 32-bit integer.
    ;   lParam  = the port which the debugger client is listening on.</em>
    PostMessage DllCall("RegisterWindowMessage", "str", "AHK_ATTACH_DEBUGGER")
</pre>
<p>Once the debugger client is connected, it may detach without terminating the script by sending the "detach" DBGp command.</p>

<h2>Script Showcase</h2>
<p>See <a href="scripts/">this page</a> for some useful scripts.</p>
</body>
</html>
